import matplotlib.pyplot as plt
import math


def plot_data():
    data = []
    with open('./output/A_output1.txt', 'r') as file:
        for line in file.readlines():
            line = line.strip('\n')
            line = line.split()
            data.append(line)

    # read in points
    knots = []
    true_value = []
    ppspline = []
    bspline = []

    for i in range(0, int(len(data)/10)):
        if i <= len(data):
            j = i*10
            num = data[j][3]
            knots.append(data[j + 2])
            true_value.append(data[j + 4])
            ppspline.append(data[j + 6])
            bspline.append(data[j + 8])
            x = []
            y = []
            z1 = []
            z2 = []
            z3 = []
            z4 = []
            for k in range(0, len(knots[i])):
                x.append(float(knots[i][k]))
                y.append(float(true_value[i][k]))
                z1.append(float(ppspline[i][k]))
                z2.append(float(bspline[i][k]))

            plt.plot(x, y, label='f(x)')
            plt.plot(x, z1, label='ppspline')
            plt.plot(x, z2, label='bspline')
            plt.title('when knots = '+num)
            plt.legend()
            plt.savefig("./pic/A1_"+num+".png")
            plt.show()


def plot_error():
    error = []
    with open('./output/A_output2.txt', 'r') as file:
        for line in file.readlines():
            line = line.strip('\n')
            line = line.split()
            error.append(line)

    num = []
    pp_error = []
    b_error = []
    log_interval = []
    log_pp_error = []
    log_b_error = []

    for i in range(0, int(len(error)/4)):
        if i <= len(error):
            j = i*4
            num.append(float(error[j][3]))
            log_interval.append(math.log(2/float(error[j][3])))
            pp_error.append(float(error[j + 1][3]))
            b_error.append(float(error[j + 2][3]))
            log_pp_error.append(math.log(float(error[j + 1][3])))
            log_b_error.append(math.log(float(error[j + 2][3])))

    plt.plot(num, pp_error, label='ppspline')
    plt.plot(num, b_error, label='bspline')
    plt.title("error of spline interpolation")
    plt.legend()
    plt.savefig("./pic/A_error.png")
    plt.show()

    plt.plot(log_interval, log_pp_error, label='ppspline')
    plt.plot(log_interval, log_b_error, label='bspline')
    plt.title("error convergence of spline interpolation")
    plt.legend()
    plt.savefig("./pic/A_error_convergence.png")
    plt.show()


plot_data()
plot_error()
